import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    products: [
      { name: '手机', price: 1000 },
      { name: '电脑', price: 2000 },
      { name: '键盘', price: 200 }
    ],
    cart: {
      '手机': 1,
      '电脑': 1,
      '键盘': 1
    }
  },
  mutations: {
    addToCart(state, product) {
      Vue.set(state.cart, product.name, (state.cart[product.name] || 0) + 1)
    },
    removeFromCart(state, product) {
      if (state.cart[product.name] > 0) {
        Vue.set(state.cart, product.name, state.cart[product.name] - 1)
      }
    }
  },
  getters: {
    totalPrice: state => {
      let total = 0
      for (let product in state.cart) {
        total += state.cart[product] * state.products.find(p => p.name === product).price
      }
      return total
    }
  }
})

export default store
//